import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface SystemSettings {
  hospital: {
    name: string
    code: string
    address: string
    phone: string
    fax: string
    email: string
    website: string
    logo: string
    description: string
    director: string
    established: string
    level: string
    beds: number
    departments: number
  }
  business: {
    workingHours: {
      weekdays: { start: string; end: string }
      weekends: { start: string; end: string }
      holidays: boolean
    }
    appointmentSettings: {
      advanceBookingDays: number
      maxAppointmentsPerDay: number
      cancellationDeadline: number
      reminderSettings: {
        enabled: boolean
        advanceHours: number
        methods: string[]
      }
    }
    paymentSettings: {
      methods: string[]
      autoInvoice: boolean
      taxRate: number
    }
  }
  security: {
    passwordPolicy: {
      minLength: number
      requireUppercase: boolean
      requireLowercase: boolean
      requireNumbers: boolean
      requireSpecialChars: boolean
      expirationDays: number
    }
    sessionSettings: {
      timeoutMinutes: number
      maxConcurrentSessions: number
    }
    auditSettings: {
      enabled: boolean
      retentionDays: number
    }
  }
  system: {
    backup: {
      enabled: boolean
      frequency: 'daily' | 'weekly' | 'monthly'
      retentionDays: number
      location: string
    }
    notifications: {
      email: {
        enabled: boolean
        server: string
        port: number
        username: string
        password: string
        ssl: boolean
      }
      sms: {
        enabled: boolean
        provider: string
        apiKey: string
        apiSecret: string
      }
    }
    integrations: {
      his: { enabled: boolean; endpoint: string; apiKey: string }
      lis: { enabled: boolean; endpoint: string; apiKey: string }
      pacs: { enabled: boolean; endpoint: string; apiKey: string }
    }
  }
  interface: {
    theme: 'light' | 'dark' | 'auto'
    language: string
    dateFormat: string
    timeFormat: string
    currency: string
    timezone: string
    pageSize: number
    autoSave: boolean
  }
}

export interface UserPreferences {
  id: string
  userId: string
  theme: 'light' | 'dark' | 'auto'
  language: string
  dashboard: {
    layout: 'grid' | 'list'
    widgets: Array<{
      id: string
      name: string
      position: { x: number; y: number }
      size: { width: number; height: number }
      visible: boolean
    }>
  }
  shortcuts: Array<{
    key: string
    action: string
    description: string
  }>
  notifications: {
    desktop: boolean
    email: boolean
    sms: boolean
    categories: Record<string, boolean>
  }
  privacy: {
    showOnlineStatus: boolean
    shareActivity: boolean
    allowDataCollection: boolean
  }
}

export const useSettingsStore = defineStore('settings', () => {
  const systemSettings = ref<SystemSettings>({
    hospital: {
      name: '云医通医院',
      code: 'YYT001',
      address: '北京市朝阳区xxx街道xxx号',
      phone: '010-12345678',
      fax: '010-12345679',
      email: 'info@yythos.com',
      website: 'www.yythos.com',
      logo: '/logo.png',
      description: '专业的医疗服务机构，致力于为患者提供优质的医疗服务',
      director: '张院长',
      established: '1998-03-15',
      level: '三甲医院',
      beds: 500,
      departments: 15
    },
    business: {
      workingHours: {
        weekdays: { start: '08:00', end: '17:30' },
        weekends: { start: '08:00', end: '12:00' },
        holidays: false
      },
      appointmentSettings: {
        advanceBookingDays: 30,
        maxAppointmentsPerDay: 100,
        cancellationDeadline: 2,
        reminderSettings: {
          enabled: true,
          advanceHours: 24,
          methods: ['短信', '微信']
        }
      },
      paymentSettings: {
        methods: ['现金', '银行卡', '微信', '支付宝', '医保'],
        autoInvoice: true,
        taxRate: 0.06
      }
    },
    security: {
      passwordPolicy: {
        minLength: 8,
        requireUppercase: true,
        requireLowercase: true,
        requireNumbers: true,
        requireSpecialChars: false,
        expirationDays: 90
      },
      sessionSettings: {
        timeoutMinutes: 30,
        maxConcurrentSessions: 3
      },
      auditSettings: {
        enabled: true,
        retentionDays: 365
      }
    },
    system: {
      backup: {
        enabled: true,
        frequency: 'daily',
        retentionDays: 30,
        location: '/backup'
      },
      notifications: {
        email: {
          enabled: true,
          server: 'smtp.example.com',
          port: 587,
          username: 'noreply@yythos.com',
          password: '',
          ssl: true
        },
        sms: {
          enabled: true,
          provider: 'aliyun',
          apiKey: '',
          apiSecret: ''
        }
      },
      integrations: {
        his: { enabled: false, endpoint: '', apiKey: '' },
        lis: { enabled: false, endpoint: '', apiKey: '' },
        pacs: { enabled: false, endpoint: '', apiKey: '' }
      }
    },
    interface: {
      theme: 'light',
      language: 'zh-CN',
      dateFormat: 'YYYY-MM-DD',
      timeFormat: 'HH:mm',
      currency: 'CNY',
      timezone: 'Asia/Shanghai',
      pageSize: 20,
      autoSave: true
    }
  })

  const userPreferences = ref<UserPreferences>({
    id: 'PREF001',
    userId: 'U001',
    theme: 'light',
    language: 'zh-CN',
    dashboard: {
      layout: 'grid',
      widgets: [
        {
          id: 'patients-today',
          name: '今日患者',
          position: { x: 0, y: 0 },
          size: { width: 4, height: 2 },
          visible: true
        },
        {
          id: 'appointments-pending',
          name: '待处理预约',
          position: { x: 4, y: 0 },
          size: { width: 4, height: 2 },
          visible: true
        },
        {
          id: 'revenue-chart',
          name: '收入趋势',
          position: { x: 0, y: 2 },
          size: { width: 8, height: 4 },
          visible: true
        }
      ]
    },
    shortcuts: [
      { key: 'Ctrl+N', action: 'new-patient', description: '新增患者' },
      { key: 'Ctrl+A', action: 'new-appointment', description: '新增预约' },
      { key: 'Ctrl+D', action: 'dashboard', description: '返回首页' }
    ],
    notifications: {
      desktop: true,
      email: true,
      sms: false,
      categories: {
        'appointment': true,
        'patient': true,
        'finance': false,
        'system': true
      }
    },
    privacy: {
      showOnlineStatus: true,
      shareActivity: false,
      allowDataCollection: true
    }
  })

  const loading = ref(false)

  // 获取系统设置
  const getSystemSettings = async () => {
    loading.value = true
    try {
      await new Promise(resolve => setTimeout(resolve, 500))
      return systemSettings.value
    } finally {
      loading.value = false
    }
  }

  // 更新系统设置
  const updateSystemSettings = async (section: keyof SystemSettings, settings: any) => {
    loading.value = true
    try {
      systemSettings.value[section] = { ...systemSettings.value[section], ...settings }
      await new Promise(resolve => setTimeout(resolve, 500))
      return systemSettings.value[section]
    } finally {
      loading.value = false
    }
  }

  // 重置系统设置
  const resetSystemSettings = async (section?: keyof SystemSettings) => {
    loading.value = true
    try {
      // 这里可以从服务器获取默认设置
      await new Promise(resolve => setTimeout(resolve, 500))
      return true
    } finally {
      loading.value = false
    }
  }

  // 获取用户偏好
  const getUserPreferences = async (userId: string) => {
    loading.value = true
    try {
      await new Promise(resolve => setTimeout(resolve, 300))
      return userPreferences.value
    } finally {
      loading.value = false
    }
  }

  // 更新用户偏好
  const updateUserPreferences = async (userId: string, preferences: Partial<UserPreferences>) => {
    loading.value = true
    try {
      userPreferences.value = { ...userPreferences.value, ...preferences }
      await new Promise(resolve => setTimeout(resolve, 300))
      return userPreferences.value
    } finally {
      loading.value = false
    }
  }

  // 测试邮件配置
  const testEmailConfig = async (config: SystemSettings['system']['notifications']['email']) => {
    loading.value = true
    try {
      await new Promise(resolve => setTimeout(resolve, 2000))
      // 模拟测试邮件发送
      return { success: true, message: '测试邮件发送成功' }
    } catch (error) {
      return { success: false, message: '测试邮件发送失败' }
    } finally {
      loading.value = false
    }
  }

  // 测试短信配置
  const testSmsConfig = async (config: SystemSettings['system']['notifications']['sms']) => {
    loading.value = true
    try {
      await new Promise(resolve => setTimeout(resolve, 2000))
      // 模拟测试短信发送
      return { success: true, message: '测试短信发送成功' }
    } catch (error) {
      return { success: false, message: '测试短信发送失败' }
    } finally {
      loading.value = false
    }
  }

  // 测试系统集成
  const testIntegration = async (type: 'his' | 'lis' | 'pacs', config: any) => {
    loading.value = true
    try {
      await new Promise(resolve => setTimeout(resolve, 2000))
      // 模拟测试集成连接
      return { success: true, message: `${type.toUpperCase()}系统连接成功` }
    } catch (error) {
      return { success: false, message: `${type.toUpperCase()}系统连接失败` }
    } finally {
      loading.value = false
    }
  }

  // 备份系统数据
  const backupSystemData = async () => {
    loading.value = true
    try {
      await new Promise(resolve => setTimeout(resolve, 5000))
      return {
        success: true,
        message: '系统备份完成',
        filename: `backup_${new Date().toISOString().split('T')[0]}.sql`,
        size: '125MB'
      }
    } finally {
      loading.value = false
    }
  }

  // 恢复系统数据
  const restoreSystemData = async (backupFile: string) => {
    loading.value = true
    try {
      await new Promise(resolve => setTimeout(resolve, 8000))
      return { success: true, message: '系统恢复完成' }
    } finally {
      loading.value = false
    }
  }

  // 清理系统数据
  const cleanupSystemData = async (options: {
    cleanLogs: boolean
    cleanTempFiles: boolean
    cleanOldBackups: boolean
    daysToKeep: number
  }) => {
    loading.value = true
    try {
      await new Promise(resolve => setTimeout(resolve, 3000))
      return {
        success: true,
        message: '系统清理完成',
        details: {
          logsDeleted: options.cleanLogs ? '125个日志文件' : '0个日志文件',
          tempFilesDeleted: options.cleanTempFiles ? '58个临时文件' : '0个临时文件',
          backupsDeleted: options.cleanOldBackups ? '12个过期备份' : '0个过期备份',
          spaceFreed: '2.3GB'
        }
      }
    } finally {
      loading.value = false
    }
  }

  // 导出设置配置
  const exportSettings = async () => {
    loading.value = true
    try {
      await new Promise(resolve => setTimeout(resolve, 1000))
      const config = {
        systemSettings: systemSettings.value,
        exportDate: new Date().toISOString(),
        version: '1.0.0'
      }
      return {
        success: true,
        data: JSON.stringify(config, null, 2),
        filename: `settings_export_${new Date().toISOString().split('T')[0]}.json`
      }
    } finally {
      loading.value = false
    }
  }

  // 导入设置配置
  const importSettings = async (configData: string) => {
    loading.value = true
    try {
      await new Promise(resolve => setTimeout(resolve, 1000))
      const config = JSON.parse(configData)
      if (config.systemSettings) {
        systemSettings.value = config.systemSettings
        return { success: true, message: '设置导入成功' }
      }
      throw new Error('无效的配置文件')
    } catch (error) {
      return { success: false, message: '设置导入失败：配置文件格式错误' }
    } finally {
      loading.value = false
    }
  }

  // 获取系统状态
  const getSystemStatus = async () => {
    loading.value = true
    try {
      await new Promise(resolve => setTimeout(resolve, 1000))
      return {
        server: {
          status: 'running',
          uptime: '15天 6小时 32分钟',
          cpu: '25%',
          memory: '68%',
          disk: '45%'
        },
        database: {
          status: 'running',
          connections: 8,
          maxConnections: 100,
          size: '2.5GB'
        },
        services: {
          webServer: 'running',
          emailService: 'running',
          smsService: 'running',
          backupService: 'running'
        }
      }
    } finally {
      loading.value = false
    }
  }

  return {
    systemSettings,
    userPreferences,
    loading,
    getSystemSettings,
    updateSystemSettings,
    resetSystemSettings,
    getUserPreferences,
    updateUserPreferences,
    testEmailConfig,
    testSmsConfig,
    testIntegration,
    backupSystemData,
    restoreSystemData,
    cleanupSystemData,
    exportSettings,
    importSettings,
    getSystemStatus
  }
}, {
  persist: {
    key: 'settings-store',
    storage: localStorage,
    paths: ['systemSettings', 'userPreferences']
  }
})